import router from "@/router/index";
import { LOGIN_URL } from "@/config/config";
import type { RouteRecordRaw } from "vue-router";
import { useUserStore } from "@/store/modules/user";
import { useAuthStore } from "@/store/modules/auth";

// 引入 views 文件夹下所有 vue 文件
const modules = import.meta.glob("@/views/**/*.vue");

/**
 * @description 初始化动态路由
 */
export const initDynamicRouter = async () => {
  const userStore = useUserStore();
  const authStore = useAuthStore();
  try {
    // 获取菜单列表 && 按钮权限列表
    authStore.getAuthMenuList();
    // await authStore.getAuthButtonList();
    authStore.flatMenuListGet.forEach((item: any) => {
      item.children && delete item.children;
      if (item.component && typeof item.component == "string") {
        item.component = modules["/src/views" + item.component + ".vue"];
      }
      if (item.meta.isFull) {
        router.addRoute(item as unknown as RouteRecordRaw);
      } else {
        router.addRoute("Layout", item as unknown as RouteRecordRaw);
      }
    });
  } catch (error) {
    // 当按钮 || 菜单请求出错时，重定向到登陆页
    userStore.SET_TOKEN("");
    router.replace(LOGIN_URL);
    return Promise.reject(error);
  }
};
